<?php
/**
 * funadmin
 * ============================================================================
 * 版权所有 2018-2027 funadmin，并保留所有权利。
 * 网站地址: http://www.Funadmin.com
 * ----------------------------------------------------------------------------
 * 采用最新Thinkphp6实现
 * ============================================================================
 * Author: yuege
 * Date: 2019/11/27
 */

namespace app\frontend\controller;

use app\common\controller\Frontend;
use app\common\model\Member as MemberModel;
use app\common\model\MemberAccount;
use app\common\model\MemberThird;
use app\common\service\MemberService;
use EasyWeChat\Factory;
use EasyWeChat\OfficialAccount\Application;
use Exception;
use think\App;
use think\facade\Db;

class Member extends Frontend
{

    protected Application $wechat;

    public function __construct(App $app)
    {
        parent::__construct($app);
        if (!$this->member) $this->redirect(__u('login/index'));
        $this->modelClass = new MemberModel();
        $this->assign('member', $this->member);
        $this->assign('action', request()->action());
        $this->wechat = Factory::officialAccount(config('easywechat.OfficialAccount'));
    }

    /**
     * @return \think\Response
     * 个人首页
     */
    public function index()
    {
        $third = MemberThird::where('member_id', $this->member['id'])->find();
        $this->assign('third', $third);
        return view('index', $this->data);
    }

    public function withdraw()
    {
        if ($this->request->isPost()) {
            $money = (int)input('money');
            if ($money <= 0) {
                throw new Exception('金额未填写');
            }
            $member = $this->modelClass->find($this->member['id']);
            $this->modelClass->where('id', $this->member['id'])->update([
                'money_now' => Db::raw('money_now-' . $money),
                'money_frozen' => Db::raw('money_frozen+' . $money),
                'money_consume' => Db::raw('money_consume+' . $money),
            ]);
            MemberAccount::insert([
                'member_id' => $member['id'],
                'money_before' => $member['money_now'],
                'money_now' => $member['money_now'] - $money,
                'money_change' => $money,
                'money_all' => $member['money_all'],
                'money_consume' => $member['money_consume'],
                'money_frozen' => $money,
                'type' => MemberAccount::TypeWithdraw,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            $this->success('提交成功！');
        }
        $third = MemberThird::where('member_id', $this->member['id'])->find();
        $this->assign('third', $third);
        return \view('', $this->data);
    }

    public function log()
    {
        $account = MemberAccount::where('member_id', $this->member['id'])
            ->where('status', '<>', MemberAccount::StatusDeleted)
            ->order('create_time', 'desc')
            ->with('member')
            ->paginate();
//        foreach ($account as &$item) {
//            $item['type_str'] = $item['type'] == MemberAccount::TypeWithdraw ? '提现' : '充值';
//            $item['status_str'] = $item['status'] == MemberAccount::StatusVerify ? '审核中' : ((MemberAccount::StatusPaying ? '打款中' : MemberAccount::StatusSuccess) ? '已到账' : '已拒绝');
//        }
        $this->assign('list', $account);
        return view('', $this->data);
    }

    /**
     * @return \think\Response
     * 其他个人主页
     */
//    public function home()
//    {
//        $id = $this->request->param('id');
//        $name = $this->request->param('name');
//        if ($id) {
//            $ouser = $this->modelClass->find($id);
//        } elseif ($name) {
//            $ouser = $this->modelClass->where('username', $name)->find();
//            if (!$ouser) $this->error('error/err');
//            $id = $ouser->id;
//        } else {
//            $id = session('member.id');
//            $ouser = session('member');
//        }
//        if (!$ouser) {
//            $this->redirect(__u('login/index'));
//        }
//        View::assign('ouser', $ouser);
//        return view();
//
//    }

    /**
     * @return \think\Response
     * 设置
     */
//    public function set()
//    {
//        if ($this->request->isPost()) {
//            $data = $this->request->post();
//            if (isset($data['avatar'])) {
//                $save = $member->save($data);
//            } elseif ($member->email == $data['email']) {
//                $save = $member->save($data);
//            } else {
//                $rule = [
//                    'email' => 'require|unique:member'
//                ];
//                try {
//                    $this->validate($data, $rule);
//                } catch (ValidateException $e) {
//                    $this->error(lang($e->getMessage()));
//                }
//                $save = $member->save($data);
//            }
//            if (!$save) $this->error(lang('modified failed'));
//            session('member', $member);
//            $this->success(lang('modified Successfully'));
//
//        }
//        $province = $this->getProvinces(0);
//        View::assign('province', $province);
//        return view();
//    }

    //修改密码
//    public function repass()
//    {
////        if (!$this->isLogin()) $this->redirect(__u('login/index'));
//        if ($this->request->isPost()) {
////            $member = $this->isLogin();
//            $data = $this->request->post();
//            $validate = new \app\frontend\validate\MemberValidate();
//            $res = $validate->scene('setPass')->check($data);
//            if (!$res) {
//                $this->error($validate->getError());
//            }
//            $old = strip_tags($data['oldpassword']);
//            $pass = strip_tags($data['password']);
//            $repass = strip_tags($data['repassword']);
//            if (!password_verify($old, $member['password'])) $this->error(lang('Old password error'));
//            if ($pass != $repass) $this->error(lang('Repeat password error'));
//            $member->password = password_hash($data['password'], PASSWORD_BCRYPT);
//            if (!$member->save()) $this->error(lang('edit failed'));
//            $this->success(lang('edit successful'));
//        }
//    }

    //获取地区
//    public function getProvinces($pid = 0)
//    {
//
//        $pid = $this->request->param('pid') ? $this->request->param('pid') : $pid;
//        $list = Db::name('provinces')->where('pid', $pid)->cache(true)->select();
//        if ($this->request->isAjax()) {
//            $this->success('', '', $list);
//        } else {
//            return $list;
//        }
//    }

    public function bindopenid()
    {
        if ($code = input('code')) {
            $user = $this->wechat->oauth->userFromCode($code);
            if ($user->getId()) {
                $thirdMember = MemberService::instance()->AddMemberThird($user, $this->member['id']);
                session('openid', $user->getId());
                session('muser', $thirdMember);
            }
        } else {
            $url = $this->wechat->oauth->redirect($this->request->domain() . url('frontend/member/bindopenid'));
            $this->redirect($url);
        }
    }


    /**
     * @return \think\Response
     * 退出
     */
    public function logout()
    {
        logout();
        $this->success('退成成功！', __u('login/index'));

    }

}